# Created by 黄景涛
# DATE: 2025/2/25

import re
import warnings
import requests
from urllib.parse import urljoin
from utils.auth.V5.encrypt import encrypt_password


"""
基础登录至蓝鲸控制台
"""


def bk_login(platform_login_url: str, username: str, password: str, is_encrypt: bool):
    """
    :param platform_login_url: 平台登录的统一url
    :param username: 用户名
    :param password: 密码
    :param is_encrypt: 是否加密
    :return:
    """
    warnings.filterwarnings('ignore')
    # 公共配置
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/115.0.0.0 Safari/537.36",
    }

    # platform_login_url校验
    try:
        re.search(r"(^http.*\.(?:com|net)/login/)", platform_login_url).group(1)
    except AttributeError:
        raise AttributeError(f'platform_login_url输入格式有误，请检查!')

    # 提取base域名
    base_host = re.search(r"(http.*\.(?:com|net))", platform_login_url).group(1)

    session = requests.session()
    login_page = session.get(platform_login_url, headers=headers, verify=False)
    assert login_page.status_code == 200, f'蓝鲸登陆页面访问失败，响应码：{login_page.status_code}'

    bklogin_csrftoken = login_page.cookies.get('bklogin_csrftoken')
    password_rsa_public_key = re.search(r'PASSWORD_RSA_PUBLIC_KEY = "(.*?)"', login_page.text).group(1)

    # 登录参数
    login_data = {
        "csrfmiddlewaretoken": bklogin_csrftoken,
        "username": username,
        "password": encrypt_password(password, password_rsa_public_key) if is_encrypt else password,
        "next": "",
        "app_id": ""
    }

    login_response = session.post(platform_login_url, data=login_data, headers=headers, verify=False,
                                  allow_redirects=False)
    assert login_response.status_code in (301, 302), f'post登录失败，响应状态码：{login_response.status_code}'

    redirect_url = urljoin(base_host, login_response.headers.get('Location'))
    console_page = session.get(redirect_url, headers=headers, verify=False)
    assert console_page.status_code == 200, f'蓝鲸控制台访问失败'

    return session
